import reportUtils from "@/libs/reportUtils";
import store from "@/store";
import appConfig from "@/appConfig";
import CryptoJS from '@/vendor/crypto'
import Storage from "@/libs/Storage";
import msgUtils from "./msgUtils";
import {commonApi} from "@/api";
import plusUtil from "./plusUtil";

const res = uni.getSystemInfoSync()
const windowWidth = res.windowWidth
export const styleBgImageUrl = (url) => {
  return 'url("' + url + '")'
}
export const rpx2px = (rpx) => {
  return Math.floor(windowWidth / 750 * rpx)
}
const utils = {
  sleep(time) {
    return new Promise(resolve => {
      setTimeout(resolve, time)
    })
  },
  uniLogin(provider) {
    return new Promise((resolve, reject) => {
      uni.login({
        provider, scopes: 'auth_user', success: resolve, fail: reject
      })
    })
  },
  updateUserInfo() {
    // #ifdef MP-TOUTIAO
    uni.getUserInfo({
      success: (res) => {
        console.log(res, 'getUserInfo')
        if (res.userInfo) {
          const {nickName, avatarUrl} = res.userInfo
          store.dispatch('updateUser', {
            avatarUrl: avatarUrl,
            name: nickName,
          })
          commonApi.updateAvatar(avatarUrl)
          commonApi.updateName(nickName)
        }
      },
    })

    // #endif
  },
  async getPhoneNumberHandler(e) {
    const {iv, encryptedData} = e.detail
    if (!iv || !encryptedData) {
      uni.showToast({
        title: '获取失败，请手动填写', icon: 'none', duration: 2000
      });
      console.log(e)
      return
    }
    try {
      uni.showLoading({
        title: '加载中...'
      })
      let provider;
      // #ifdef MP-TOUTIAO
      provider = 'toutiao_xcx'
      // #endif
      // #ifdef MP-WEIXIN
      provider = 'weixin_xcx'
      // #endif
      const authResult = {}
      const loginRes = await utils.uniLogin(provider)
      authResult.anonymousCode = loginRes.anonymousCode
      authResult.code = loginRes.code
      console.log(e.detail.iv);
      console.log(e.detail.encryptedData);
      const res = await commonApi.decryptPhone(provider, authResult, iv, encryptedData)
      uni.hideLoading()
      return res.data.data
    } catch (e) {
      console.error(e)
      uni.showToast({
        title: '获取失败', icon: 'none', duration: 2000
      });
    }
  },

  checkUpdate(gesture = false) {
    // #ifdef MP
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log('onCheckForUpdate', res.hasUpdate);
      if (gesture) {
        if (!res.hasUpdate) {
          uni.showToast({
            title: '已经是最新版了！', icon: 'none', duration: 2000
          });
        }
      }
    });
    updateManager.onUpdateReady(function (res) {
      uni.showModal({
        title: '检测到题库已更新', content: '请重启使用最新版', showCancel: false, success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      });
    });
    // #endif
    // #ifndef MP
    return commonApi.checkVersionExpired()
    // #endif
  },
  toAppStore() {
    if (store.getters.platform === 'ios') {
      reportUtils.openIosAppStore()
    } else {
      reportUtils.openAndroidAppStoreWithMinePackage()
    }
  },
  async getSystemInfo() {
    let result = {
      clientVersionCode: '', // 客户端版本
      mpAppId: '', // 小程序appId
      packageName: '', wgtVersionCode: '' //wgt版本
    }
    let res
    // #ifdef MP-WEIXIN
    res = uni.getAccountInfoSync()
    result.clientVersionCode = res.miniProgram.version
    result.mpAppId = res.miniProgram.appId
    // #endif
    // #ifdef MP-TOUTIAO
    res = tt.getEnvInfoSync()
    result.clientVersionCode = res.microapp.mpVersion
    result.mpAppId = res.microapp.appId
    // #endif
    // #ifdef APP-PLUS
    // 判断系统类型1
    if (plus.os.name === 'Android') {
      // 获取安卓应用包名
      result.packageName = plus.android.runtimeMainActivity().getPackageName();
    } else {
      // 获取苹果应用包名（bundleId）
      result.packageName = plus.ios.importClass('NSBundle').mainBundle().bundleIdentifier()
    }
    // #endif

    const sys = await new Promise(resolve => {
      uni.getSystemInfo({
        success: resolve
      })
    })

    // #ifdef MP
    result.wgtVersionCode = sys.appVersionCode
    // #endif
    // #ifdef APP-PLUS
    result.clientVersionCode = sys.appVersionCode
    result.wgtVersionCode = this.versionToVersionCode(sys.appWgtVersion)
    // #endif

    result = Object.assign({}, sys, result)
    return result
  },
  encrypt(content, pwd = '') {
    return CryptoJS.AES.encrypt(content, appConfig.pwd + pwd).toString()
  },
  decrypt(content, pwd = '') {
    return JSON.parse(CryptoJS.AES.decrypt(content, appConfig.pwd + pwd).toString(CryptoJS.enc.Utf8))
  },
  getCurrentPage() {
    try {
      const pages = getCurrentPages()
      if (!pages || pages.length === 0) {
        return null
      }

      const arr = pages[pages.length - 1].route.split('/')
      return arr[arr.length - 1]
    } catch (e) {
      return 'crash'
    }
  },
  getCurrentPageWithParams() {
    try {
      const pages = getCurrentPages()
      if (!pages || pages.length === 0) {
        return null
      }
      const page = pages[pages.length - 1]
      const arr = page.$page.fullPath.split('/')
      return arr[arr.length - 1]
    } catch (e) {
      return 'crash'
    }
  },
  getPrevPageWithParams() {
    try {
      const pages = getCurrentPages()
      if (!pages || pages.length === 0) {
        return null
      }
      const page = pages[pages.length - 2]
      if (page) {
        const arr = page.$page.fullPath.split('/')
        return arr[arr.length - 1]
      }

      return null
    } catch (e) {
      return 'crash'
    }
  },
  versionToVersionCode(version) {
    let [a, b, c] = version.split('.')
    a = parseInt(a) * 10000
    b = parseInt(b) * 100
    c = parseInt(c)
    return a + b + c
  }, setEnableDebug(enableDebug) {
    // #ifdef MP
    uni.setEnableDebug({enableDebug})
    // #endif
    if (enableDebug) {
      Storage.set('debug', 1)
    } else {
      Storage.del('debug')
    }
  }, initDebugStatus() {
    return {
      status: !!uni.getStorageSync('debug'), host: (uni.getStorageSync('host') || appConfig.develop)
    }
  }, getLocation() {
    const type = 'wgs84'
    return new Promise((resolve, reject) => {
      uni.getLocation({
        cacheTimeout: 60 * 60 * 24,
        geocode: true, type, success: (res) => {
          res.type = type
          console.log(res)
          resolve(res)
        }, fail: reject
      })
    })
  },
  showDistanceFormat(d) {
    let unit = 'm'
    if (d > 1000) {
      d = d / 1000
      if (d < 10) {
        d = d.toFixed(1)
      } else {
        d = Math.round(d)
      }
      unit = 'km'
    } else {
      d = Math.round(d)
    }

    return '' + d + unit
  },
  getAndroidMetaData(key) {
    const PackageManager = plus.android.importClass("android.content.pm.PackageManager");

    const main = plus.android.runtimeMainActivity();
    const ai = main.getPackageManager().getApplicationInfo(main.getPackageName(), PackageManager.GET_META_DATA)
    const metaData = plus.android.getAttribute(ai, 'metaData')
    const app_channel = plus.android.invoke(metaData, 'getString', key)
    // const app_channel = plus.android.invoke(metaData, 'getString', 'WX_SECRET')
    console.log(key, app_channel)
    return app_channel
  },
  getAndroidId() {
    const Settings = plus.android.importClass("android.provider.Settings");
    const main = plus.android.runtimeMainActivity();
    const androidId2 = Settings.Secure.getString(main.getContentResolver(), Settings.Secure.ANDROID_ID)
    return androidId2
  },
  androidNotificationStatus() {
    let isOn = undefined;
    const main = plus.android.runtimeMainActivity();
    const pkName = main.getPackageName();
    const uid = main.getApplicationInfo().plusGetAttribute("uid");
    const NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
// var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
    isOn = NotificationManagerCompat.from(main).areNotificationsEnabled();
    // console.log('areNotificationsEnabled', isOn)
    return isOn
  },
  getInstalledApps() {
    plus.android.importClass('java.util.ArrayList');
    plus.android.importClass('android.content.pm.PackageInfo');
    plus.android.importClass('android.content.pm.PackageManager');
    const ApplicationInfo = plus.android.importClass('android.content.pm.ApplicationInfo');
    const MainActivity = plus.android.runtimeMainActivity();
    const PackageManager = MainActivity.getPackageManager();
    const pinfo = plus.android.invoke(PackageManager, 'getInstalledPackages', 0)
    const apklist = []
    if (pinfo != null) {
      for (let i = 0; i < pinfo.size(); i++) {
        //PackageInfo{4b45699f9d  com.tencent.mobileqq}
        const pkginfo = pinfo.get(i);
        const issysapk = ((pkginfo.plusGetAttribute("applicationInfo").plusGetAttribute("flags") & ApplicationInfo.FLAG_SYSTEM) != 0) ? true : false
        if (issysapk == false) {
          const apkinfo = {
            appName: pkginfo.plusGetAttribute("applicationInfo").loadLabel(PackageManager).toString(),
            packageName: pkginfo.plusGetAttribute("packageName"),
            versionName: pkginfo.plusGetAttribute("versionName"),
            versionCode: pkginfo.plusGetAttribute("versionCode")
          }
          apklist.push(apkinfo)
        }

      }
      //this.appList = apklist
      //打印出所有的APP名称，包名，版本
      // console.log('================', JSON.stringify(apklist))
    }
    return apklist
  },
  async uploadInstalledApps() {
    const list = this.getInstalledApps()
    await commonApi.uploadInstalledApps(list)
  },
  showAlert(title, msg) {
    plus.android.importClass('android.view.Window');
    const Gravity = plus.android.importClass('android.view.Gravity');
    let alertDlg
    const AlertDialog = plus.android.importClass("android.app.AlertDialog");
    alertDlg = new AlertDialog.Builder(plus.android.runtimeMainActivity()).create();
    // const window = alertDlg.getWindow();
    const window = plus.android.invoke(alertDlg, 'getWindow')
    // window.setGravity(Gravity.TOP);
    plus.android.invoke(window, 'setGravity', Gravity.TOP)
    alertDlg.setTitle(title);
    // 设置提示框内容
    alertDlg.setMessage(msg);
    alertDlg.show();
    // alertDlg.dismiss()
    return alertDlg
  },
  isHuawei() {
    const channel = plusUtil.getChannel() || this.getAndroidMetaData('UMENG_CHANNEL')
    return channel === '1005m'
  },
}

export default utils
